#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <strings.h>
#include <string.h>
#include <string>
#include <errno.h>
#include "log.hpp"

using namespace std;
Log lg;

void Usage(string proc)
{
    cout << proc << "[ ip + port]" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[1]);
        exit(1);
    }

    uint16_t port = stoi(argv[2]);
    string ip = argv[1];

    int sockfd = socket(AF_INET, SOCK_STREAM, 0); // 放前面，错了咱就不玩了
    if (sockfd < 0)
    {
        lg("fatal", "sock create fail errno:%d strerror:%d", errno, strerror(errno));
        return 1;
    }

    lg("info", "sock create sucess errno:%d strerror:%d", errno, strerror(errno));

    struct sockaddr_in local;
    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = inet_addr(ip.c_str());

    socklen_t len = sizeof(local);
    if (connect(sockfd, (struct sockaddr *)&local, len) < 0) // 在这个时候，操作系统给客服端绑了一个端口
    {
        lg("fatal", "connect fail errno:%d strerror:%d", errno, strerror(errno));
        return 1;
    }

    int cnt = 5;

    string message;
    char buffer[SIZE]; // log 里面定义的

    while (cnt--)
    {
        cout << "please Enter#:";
        getline(cin, message);
        int n = write(sockfd, message.c_str(), message.size()); // 发送消息
        if (n < 0)
        {
            lg("info", "write fail errno:%d strerror:%d", errno, strerror(errno));
        }

        int size = read(sockfd, buffer, SIZE - 1);
        if (size > 0)
        {
            buffer[size] = 0;
            cout << buffer << endl;
        }
        else if (size == 0)
        {
            cout<<"no data"<<endl;
        }
        else 
        {
            cout<<"error"<<endl;
            break;
        }
    }
    close(sockfd);
    return 0;
}